package com.feixiang.springbootinit.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ws.schild.jave.AudioAttributes;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncodingAttributes;
import ws.schild.jave.MultimediaObject;

import java.io.*;

/**
 * @author feixiang
 *
 * @date 2024/10/12 15:43
 */
public class VoiceUtil {

    private static final Logger logger = LoggerFactory.getLogger(VoiceUtil.class);

    /**
     * 下载文件到本地
     *
     * @param is
     * @param targetPath
     * @return
     */
    public static File downloadFile(InputStream is, String targetPath) {
        FileOutputStream fos = null;
        try {
            File dir = new File(targetPath.substring(0, targetPath.lastIndexOf(File.separator)));
            if (!dir.exists()) {
                dir.mkdirs();
            }

            int len;
            byte[] bs = new byte[1024 * 2];

            File file = new File(targetPath);
            fos = new FileOutputStream(file);

            while ((len = is.read(bs)) != -1) {
                fos.write(bs, 0, len);
            }
            return file;
        } catch (Exception e) {
            logger.error("下载文件到本地失败：" + e.getMessage(), e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                logger.error("下载文件到本地关闭IO资源失败：" + e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * 音频格式转换
     *
     * @param sourceFilePath
     * @param targetFilePath
     * @param format            wav/mp3/amr
     * @return
     */
    public static byte[] getAudioFormatConversionBytes(String sourceFilePath,String targetFilePath,String format) {
        InputStream fis = null;
        ByteArrayOutputStream bos = null;
        byte[] bytes = null;
        try {
            File sourceFile = new File(sourceFilePath);
            if (sourceFile.isFile()) {
                File targetFile = new File(targetFilePath);

                // 音频格式转换
                audioFormatConversion(sourceFile, targetFile, format);

                fis = new FileInputStream(targetFile);
                bos = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    bos.write(buffer, 0, bytesRead);
                }
                bytes = bos.toByteArray();
            }
        } catch (Exception e) {
            logger.error("音频格式转换异常：" + e.getMessage(), e);
            return null;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                logger.error("音频格式转换资源关闭异常：" + e.getMessage(), e);
            }
        }
        return bytes;
    }

    /**
     * 音频格式转换
     *
     * @param sourceFilePath
     * @param targetFilePath
     * @param format            wav/mp3/amr
     * @return
     */
    public static InputStream getAudioFormatConversionIns(String sourceFilePath,String targetFilePath,String format) {
        try {
            File sourceFile = new File(sourceFilePath);
            if (sourceFile.isFile()) {
                File targetFile = new File(targetFilePath);

                // 音频格式转换
                audioFormatConversion(sourceFile, targetFile, format);

                return new FileInputStream(targetFile);
            }
        } catch (Exception e) {
            logger.error("音频格式转换异常：" + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 音频格式转换
     * @param source 源音频文件
     * @param target 输出的音频文件
     * @param format wav/mp3/amr
     */
    public static void audioFormatConversion(File source,File target,String format) {
        try {
            //Audio Attributes
            AudioAttributes audio = new AudioAttributes();
            switch (format) {
                case "wav":
                    audio.setCodec("pcm_s16le");
                    break;
                case "mp3":
                    audio.setCodec("libmp3lame");
                    break;
                case "amr":
                    audio.setCodec("libvo_amrwbenc");
                    break;
                default:
                    logger.error("音频格式不合法！");
                    return;
            }
            audio.setBitRate(16000);
            audio.setChannels(1);
            audio.setSamplingRate(16000);
            //Encoding attributes
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setFormat(format);
            attrs.setAudioAttributes(audio);
            //Encode
            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(source), target, attrs);
        } catch (Exception e) {
            logger.error("音频格式转换异常：" + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        try {
            File amrFile = new File("D:\\test\\7424326131957891072.amr");
            File wavFile = new File("D:\\test\\7424326131957891072_wav_3.wav");
            audioFormatConversion(amrFile, wavFile, "wav");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

